'use client';

import { useState, useEffect } from 'react';
import AppHeader from '@/components/ui/app-header';
import { 
  BellIcon, 
  CheckCircleIcon, 
  ExclamationCircleIcon, 
  InformationCircleIcon,
  ClockIcon 
} from '@heroicons/react/24/outline';
import { notificationApi } from '@/lib/api';
import { Notification } from '@/types/notification';

export default function NotificationsPage() {
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [filter, setFilter] = useState('all'); // 'all', 'unread', 'read'
  
  useEffect(() => {
    const fetchNotifications = async () => {
      try {
        setIsLoading(true);
        setError(null);
        const data = await notificationApi.getNotifications();
        setNotifications(data);
      } catch (err) {
        console.error('获取通知失败:', err);
        setError('获取通知失败，请稍后重试');
      } finally {
        setIsLoading(false);
      }
    };
    
    fetchNotifications();
  }, []);
  
  // 标记通知为已读
  const markAsRead = async (id: string) => {
    try {
      await notificationApi.markAsRead(id);
      setNotifications(notifications.map(notification => 
        notification.id === id ? { ...notification, read: true } : notification
      ));
    } catch (err) {
      console.error('标记通知已读失败:', err);
    }
  };
  
  // 根据筛选条件过滤通知
  const filteredNotifications = notifications.filter(notification => {
    if (filter === 'all') return true;
    if (filter === 'unread') return !notification.read;
    if (filter === 'read') return notification.read;
    return true;
  });
  
  // 标记所有通知为已读
  const markAllAsRead = async () => {
    try {
      await notificationApi.markAllAsRead();
      setNotifications(notifications.map(notification => ({ ...notification, read: true })));
    } catch (err) {
      console.error('标记所有通知已读失败:', err);
    }
  };
  
  // 根据通知类型返回相应的图标
  const getNotificationIcon = (type: string) => {
    switch (type) {
      case 'TASK_ASSIGNED':
        return <CheckCircleIcon className="h-6 w-6 text-green-500" />;
      case 'PROJECT_UPDATE':
      case 'PROJECT_INVITATION':
        return <InformationCircleIcon className="h-6 w-6 text-blue-500" />;
      case 'TASK_COMMENT':
      case 'MENTION':
        return <BellIcon className="h-6 w-6 text-purple-500" />;
      default:
        return <BellIcon className="h-6 w-6 text-gray-500" />;
    }
  };

  // 将API日期转换为相对时间显示
  const getRelativeTime = (dateValue: string | Date): string => {
    const date = typeof dateValue === 'string' ? new Date(dateValue) : dateValue;
    const now = new Date();
    const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);
    
    if (diffInSeconds < 60) return `${diffInSeconds}秒前`;
    if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)}分钟前`;
    if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)}小时前`;
    if (diffInSeconds < 604800) return `${Math.floor(diffInSeconds / 86400)}天前`;
    
    // 如果超过一周，显示具体日期
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    });
  };

  return (
    <div className="min-h-screen">
      <main className="py-6 px-4 sm:px-6 lg:px-8 max-w-7xl mx-auto">
        <AppHeader
          title="通知中心"
          subtitle="查看您的所有通知"
          actions={
            <button
              onClick={markAllAsRead}
              className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-[var(--primary-color)] hover:bg-[var(--primary-hover)] focus:outline-none"
            >
              全部标为已读
            </button>
          }
        />
        
        <div className="mt-4 flex space-x-4 border-b border-gray-200">
          <button
            onClick={() => setFilter('all')}
            className={`pb-4 px-1 ${
              filter === 'all'
                ? 'border-b-2 border-[var(--primary-color)] text-[var(--primary-color)]'
                : 'text-gray-500 hover:text-gray-700 hover:border-gray-300'
            }`}
          >
            全部
          </button>
          <button
            onClick={() => setFilter('unread')}
            className={`pb-4 px-1 ${
              filter === 'unread'
                ? 'border-b-2 border-[var(--primary-color)] text-[var(--primary-color)]'
                : 'text-gray-500 hover:text-gray-700 hover:border-gray-300'
            }`}
          >
            未读
          </button>
          <button
            onClick={() => setFilter('read')}
            className={`pb-4 px-1 ${
              filter === 'read'
                ? 'border-b-2 border-[var(--primary-color)] text-[var(--primary-color)]'
                : 'text-gray-500 hover:text-gray-700 hover:border-gray-300'
            }`}
          >
            已读
          </button>
        </div>
        
        <div className="mt-6">
          {isLoading ? (
            <div className="text-center py-12">
              <div className="animate-spin h-8 w-8 border-4 border-[var(--primary-color)] border-t-transparent rounded-full mx-auto"></div>
              <p className="mt-2 text-sm text-gray-500">加载通知中...</p>
            </div>
          ) : error ? (
            <div className="text-center py-12">
              <ExclamationCircleIcon className="h-12 w-12 text-red-500 mx-auto" />
              <h3 className="mt-2 text-sm font-medium text-gray-900">获取通知失败</h3>
              <p className="mt-1 text-sm text-gray-500">{error}</p>
            </div>
          ) : filteredNotifications.length === 0 ? (
            <div className="text-center py-12">
              <BellIcon className="h-12 w-12 text-gray-400 mx-auto" />
              <h3 className="mt-2 text-sm font-medium text-gray-900">暂无通知</h3>
              <p className="mt-1 text-sm text-gray-500">当有新通知时将在这里显示</p>
            </div>
          ) : (
            <ul className="divide-y divide-gray-200">
              {filteredNotifications.map((notification) => (
                <li
                  key={notification.id}
                  className={`py-4 ${!notification.read ? 'bg-[var(--secondary-color)] bg-opacity-30' : ''}`}
                  onClick={() => markAsRead(notification.id)}
                >
                  <div className="flex items-center space-x-4">
                    <div className="flex-shrink-0">
                      {getNotificationIcon(notification.type)}
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center justify-between">
                        <p className={`text-sm font-medium ${!notification.read ? 'text-gray-900' : 'text-gray-600'}`}>
                          {notification.title}
                        </p>
                        <p className="text-xs text-gray-500">{getRelativeTime(notification.createdAt)}</p>
                      </div>
                      <p className="text-sm text-gray-500 truncate">{notification.content}</p>
                    </div>
                    {!notification.read && (
                      <div className="flex-shrink-0">
                        <div className="h-2 w-2 rounded-full bg-[var(--primary-color)]"></div>
                      </div>
                    )}
                  </div>
                </li>
              ))}
            </ul>
          )}
        </div>
      </main>
    </div>
  );
} 